import { isH5 } from './platform'

export function getPropByPath(obj, path) {
  let tempObj = obj
  path = path.replace(/\[(\w+)\]/g, '.$1')
  path = path.replace(/^\./, '')

  const keyArr = path.split('.')
  let i = 0

  for (let len = keyArr.length; i < len - 1; ++i) {
    const key = keyArr[i]
    if (key in tempObj) {
      tempObj = tempObj[key]
    } else {
      throw new Error('please transfer a valid prop path to form item!')
    }
  }
  return {
    target: tempObj,
    key: keyArr[i],
    value: tempObj[keyArr[i]]
  }
}

let scrollTop = 0

/**
 * 禁用页面滚动
 */
export function disablePageScroll() {
  if (isH5) {
    // H5环境
    scrollTop = document.documentElement.scrollTop || document.body.scrollTop
    document.body.style.position = 'fixed'
    document.body.style.width = '100%'
    document.body.style.top = -scrollTop + 'px'
    document.body.style.overflow = 'hidden'
  } else {
    // 小程序环境
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 0
    })
  }
}

/**
 * 启用页面滚动
 */
export function enablePageScroll() {
  if (isH5) {
    // H5环境
    document.body.style.position = ''
    document.body.style.width = ''
    document.body.style.top = ''
    document.body.style.overflow = ''
    window.scrollTo(0, scrollTop)
  }
} 